package daoImp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

import util.DateUtil;

import model.NewsInfo;

import dao.NewsDAO;

public class NewsDAOImp implements NewsDAO{
	private static NewsDAOImp uniqueInstance = new NewsDAOImp();
	private ConnectionPool pool = ConnectionPool.getInstance();
	public static NewsDAO getInstance() {
		return uniqueInstance;
	}

	private NewsDAOImp() {
	}

	public ArrayList<NewsInfo> getNewsAboutTrend(String trend, Date date) {
		ArrayList<NewsInfo> newsList = new ArrayList<NewsInfo>();
		try {
			Connection connection;
			try {
				connection = pool.getConnection();
			} catch (Exception e) {
				e.printStackTrace();
				return newsList;
			}
			Statement stmt = connection.createStatement();
			String dateStr = DateUtil.getNewsDateStr(date);
			trend = trend.replaceAll("'", "\\\\'").replaceAll("\\)", "\\\\)").replaceAll("\\(", "\\\\(");
			String sql = "select content,url from news where trend = '" + trend + "' and date = '" + dateStr +"';";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String news = rs.getString(1);
				String url = rs.getString(2);
				NewsInfo info = new NewsInfo(news, url);
				newsList.add(info);
			}
			pool.returnConnection(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return newsList;
	}

}
